# -*- coding: utf-8 -*-

import sys
sys.path.append('../')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
from urllib.parse import urlencode
import requests, json
from common.helper import Helper

class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "平安i无忧医疗保险"

    def genProductInfo(self):
        plan = {
            # 年龄段
            "year":[str(i) for i in range(51,72)],
            #有无社保
            "socialSec":["Y","N"],
            # 保障期限
            "expire":["1年"],
            # 缴费类型
            "payType":["年缴"],
            # 恶性肿瘤保险金额
            "cancerMedical":["2000000"],
            #免赔额
            "deductible":["0","1","3"]
        }
        for v in product(plan["year"],plan["socialSec"],plan["expire"],plan["payType"],plan["cancerMedical"],plan["deductible"]):

           self.mysql.cursor.execute( domain[self.name]["insert_sql"].format(
               v[0],v[1],v[2],v[3],v[4],v[5]
            ))
           self.mysql._conn.commit()
           print( domain[self.name]["insert_sql"].format(
               v[0],v[1],v[2],v[3],v[4],v[5]
            ))
    #执行爬虫
    def requestJson(self,dt=None):

        data = {
            "DEDUCTIBLE_LIMIT": ""+dt["deductible"]+"W",
            "insurants_applyingAge_1": "{year} - 02 - 28".format(year = str(2020-int(dt["year"]))),
            "SOCIAL_SECURITY":dt["socialSec"],
            "PRODUCT_PERIOD_RULE": "1Y",
            "SHARE_NUM_1045": "1",
            "productCode": "1045",
            "appSource": "W02"
        }

        payload = urlencode(data).replace("+","")
        r = requests.post( url = domain[self.name]["url"],headers=domain[self.name]["header"],data=payload)
        if r.status_code == 200 and "成功" in r.text:
            price = Helper.decimalParse(r.json()["DATA"]["totalExpenses"])
            data = {
                "name":self.name,
                "id":dt["id"],
                "price":price
            }
            self.mysql.updatePrice( data )
        else:
            data = {
                "name":self.name,
                "id":dt["id"],
                "state":3
            }
            self.mysql.updateTask( data )
            print("\n/*产品价格更新失败:%d*/"%dt["id"])

    def main(self):

        while True:

            # 随机领取一条数据
            dt = self.mysql.randTask(self.name)

            if not dt:
                print("产品价格抓取完成~~~")

                return

                # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            self.mysql.updateTask(data)

            self.requestJson(dt)
